<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmitHandle()" label-width="80px">
      <el-form-item label="类型" prop="type">
        <el-radio v-model="dataForm.type" :label="0" :disabled="!!dataForm.id">菜单</el-radio>
        <el-radio v-model="dataForm.type" :label="1" :disabled="!!dataForm.id">按钮</el-radio>
      </el-form-item>

      <el-form-item :label="`${ dataForm.type === 0 ? '菜单' : '按钮' }名称`" prop="name">
        <el-input v-model="dataForm.name" :placeholder="`${ dataForm.type === 0 ? '菜单' : '按钮' }名称`"></el-input>
      </el-form-item>

      <el-form-item label="上级菜单" prop="parentName" class="menu-list">
        <el-popover
          ref="menuListPopover"
          placement="bottom-start"
          trigger="click">
          <el-tree
            :data="menuList"
            :props="menuListTreeProps"
            node-key="id"
            ref="menuListTree"
            @current-change="menuListTreeCurrentChangeHandle"
            :highlight-current="true"
            :expand-on-click-node="false"
            accordion>
          </el-tree>
        </el-popover>
        <el-input v-model="dataForm.parentName" v-popover:menuListPopover :readonly="true" placeholder="点击选择上级菜单">
          <i
            v-if="dataForm.parentName !== '一级菜单'" 
            slot="suffix" 
            @click="menuListTreeRemoveSelectHandle()"
            class="el-icon-circle-close el-input__icon"></i>
        </el-input>
      </el-form-item>

      <el-form-item v-if="dataForm.type === 0" label="菜单路由" prop="url">
        <el-input v-model="dataForm.url" placeholder="菜单路由"></el-input>
      </el-form-item>

      <el-form-item label="授权标识" prop="permissions">
        <el-input v-model="dataForm.permissions" placeholder="多个用逗号分隔, 如: sys:menu:save"></el-input>
      </el-form-item>

      <el-form-item v-if="dataForm.type === 0" label="排序号" prop="sort">
        <el-input-number v-model="dataForm.sort" controls-position="right" :min="0" label="排序号"></el-input-number>
      </el-form-item>

      <el-form-item v-if="dataForm.type === 0" label="菜单图标" prop="icon" class="icon-list">
        <el-popover
          ref="iconListPopover"
          placement="bottom-start"
          trigger="click"
          popper-class="mod-sys__menu-icon-popover">
          <div class="mod-sys__menu-icon-list">
            <el-button
              v-for="(item, index) in iconList"
              :key="index"
              @click="dataForm.icon = item"
              :class="{ 'is-active': dataForm.icon === item }">
              <svg class="icon-svg" aria-hidden="true"><use :xlink:href="`#${item}`"></use></svg>
            </el-button>
          </div>
        </el-popover>
        <el-input v-model="dataForm.icon" v-popover:iconListPopover :readonly="true" placeholder="菜单图标名称"></el-input>
      </el-form-item>

      <el-form-item
        v-if="dataForm.type === 0"
        v-for="(item, index) in dataForm.resourceList"
        :key="item.key"
        :prop="`resourceList.${index}.resourceUrl`"
        :rules="{ required: true, message: '必填项不能为空', trigger: 'blur' }"
        :label="index === 0 ? '菜单资源': ''"
        class="resource-list">
        <el-row>
          <el-col :span="22">
            <el-input v-model="item.resourceUrl" placeholder="资源URL">
              <el-select v-model="item.resourceMethod" slot="prepend" placeholder="请求方式">
                <el-option label="GET" value="GET"></el-option>
                <el-option label="POST" value="POST"></el-option>
                <el-option label="PUT" value="PUT"></el-option>
                <el-option label="DELETE" value="DELETE"></el-option>
              </el-select>
            </el-input>
          </el-col>
          <el-col :span="2" class="text-center">
            <el-button @click="resourceDeleteHandle(item)" size="small" type="text">删除</el-button>
          </el-col>
        </el-row>
      </el-form-item>

      <el-form-item v-if="dataForm.type === 0" :label="dataForm.resourceList.length <= 0 ? '菜单资源': ''">
        <el-button @click="resourceAddHandle()" class="aui-button--dashed w-percent-100">添加一项</el-button>
      </el-form-item>
    </el-form>
    <template slot="footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">确定</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { getIconList } from '@/utils'
export default {
  data () {
    return {
      visible: false,
      menuList: [],
      menuListTreeProps: {
        label: 'name',
        children: 'children'
      },
      iconList: [],
      dataForm: {
        id: '',
        type: 0,
        name: '',
        pid: 0,
        parentName: '一级菜单',
        url: '',
        resourceList: [],
        permissions: '',
        sort: 0,
        icon: ''
      },
      dataRule: {
        name: [
          { required: true, message: '必填项不能为空', trigger: 'blur' }
        ],
        parentName: [
          { required: true, message: '必填项不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    'dataForm.type' (val) {
      this.$refs['dataForm'].clearValidate()
    }
  },
  methods: {
    init () {
      this.visible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        this.iconList = getIconList()
        this.getMenuList().then(() => {
          if (this.dataForm.id) {
            this.getInfo()
          }
        })
      })
    },
    // 获取菜单列表
    getMenuList () {
      return this.$http.get('/sys/menu/list').then(({data}) => {
        if (!data || data.code !== 0) {
          this.menuList = []
          return this.$message.error(data.msg)
        }
        this.menuList = data.data
      })
    },
    // 获取信息
    getInfo () {
      this.$http.get(`/sys/menu/${this.dataForm.id}`).then(({data}) => {
        if (!data || data.code !== 0) {
          return this.$message.error(data.msg)
        }
        this.dataForm = data.data
        // 上级菜单树, 设置当前选中节点
        this.$refs.menuListTree.setCurrentKey(this.dataForm.pid)
        this.dataForm.parentName = this.dataForm.pid === this.$refs.menuListTree.getCurrentKey()
          ? this.$refs.menuListTree.getCurrentNode()['name']
          : '一级菜单'
      })
    },
    // 上级菜单树, 选中
    menuListTreeCurrentChangeHandle (data) {
      this.dataForm.pid = data.id
      this.dataForm.parentName = data.name
    },
    // 上级菜单树, 删除当前选中
    menuListTreeRemoveSelectHandle () {
      this.dataForm.pid = '0'
      this.dataForm.parentName = '一级菜单'
    },
    // 菜单资源, 添加
    resourceAddHandle () {
      this.dataForm.resourceList.push({
        key: new Date().getTime(),
        resourceMethod: 'GET',
        resourceUrl: ''
      })
    },
    // 菜单资源, 删除
    resourceDeleteHandle (resource) {
      this.dataForm.resourceList = this.dataForm.resourceList.filter(item => item.key !== resource.key)
    },
    // 表单提交
    dataFormSubmitHandle () {
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) {
          return false
        }
        this.$http[!this.dataForm.id ? 'post' : 'put']('/sys/menu/', this.dataForm).then(({data}) => {
          if (!data || data.code !== 0) {
            return this.$message.error(data.msg)
          }
          this.$message({
            message: '操作成功',
            type: 'success',
            duration: 1500,
            onClose: () => {
              this.visible = false
              this.$emit('refreshDataList')
            }
          })
        })
      })
    }
  }
}
</script>

<style lang="scss">
.mod-sys__menu {
  .resource-list {
    .el-select .el-input__inner {
      min-width: 110px;
      text-align: center;
    }
  }
  .menu-list,
  .icon-list {
    .el-input__inner,
    .el-input__suffix {
      cursor: pointer;
    }
  }
  &-icon-popover {
    max-width: 370px;
  }
  &-icon-list {
    padding: 0;
    margin: -8px 0 0 -8px;
    > .el-button {
      padding: 8px;
      margin: 8px 0 0 8px;
      > span {
        display: inline-block;
        vertical-align: middle;
        width: 18px;
        height: 18px;
        font-size: 18px;
      }
    }
  }
}
</style>
